package drds.server.net.packet.auth;

import java.security.NoSuchAlgorithmException;
import java.security.Security;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;

/**
 * 
 * @author 曹正辉<330937205@qq.com>
 * 
 */
public class HmacMD5 {

	public static byte[] initKey() {
		Security.addProvider(new BouncyCastleProvider());
		KeyGenerator keyGenerator = null;
		try {
			keyGenerator = KeyGenerator.getInstance("HmacMD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		SecretKey secretKey = keyGenerator.generateKey();
		return secretKey.getEncoded();
	}

	public static byte[] encode(byte[] key, byte[] data) {
		Security.addProvider(new BouncyCastleProvider());
		SecretKey secretKey = new SecretKeySpec(key, "HmacMD5");
		Mac mac = null;
		try {
			mac = Mac.getInstance(secretKey.getAlgorithm());
			mac.init(secretKey);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return mac.doFinal(data);
	}

	public static String encodeHex(byte[] key, byte[] data) {
		byte[] bytes = encode(key, data);
		return new String(Hex.encode(bytes));
	}

	/**
	 * 进行相关的摘要算法的处理展示
	 */
	public static void main(String[] args) throws Exception {
		String string = "测试";
		byte[] key = HmacMD5.initKey();
		byte[] data = HmacMD5.encode(key, string.getBytes());
		string = new String(Hex.encode(data));

		System.out.println("原文：" + string);
		System.out.println("key:" + key.toString() + "--" + key.length);
		System.out.println("密文：" + string);

	}
}